<template>
	<view class="wanl-upload">
		<!-- 上传区域 -->
		<view class="upload-area" v-if="maxCount === 1">
			<uv-upload :fileList="fileList" :name="name" multiple maxCount="1" :previewImage="previewImage"
				:deletable="deletable" @afterRead="afterRead" @delete="deletePic">
				<view class="upload-custom">
					<view class="upload-icon">
						<uv-icon name="folder" size="26"></uv-icon>
					</view>

					<text class="upload-text">{{ uploadText }}</text>
					<!-- <text class="upload-tip" v-if="showTip">{{ tipText }}</text> -->
				</view>
			</uv-upload>
		</view>
		<view class="upload-area" v-else>
			<uv-upload :fileList="fileList" :name="name" :multiple="multiple" :maxCount="maxCount"
				:previewImage="previewImage" :deletable="deletable" @afterRead="afterRead" @delete="deletePic">
				<view class="upload-custom">
					<view class="upload-icon">
						<uv-icon name="folder" size="26"></uv-icon>
					</view>

					<text class="upload-text">{{ uploadText }}</text>
					<!-- <text class="upload-tip" v-if="showTip">{{ tipText }}</text> -->
				</view>
			</uv-upload>
		</view>

		<!-- 上传进度弹窗 -->
		<uv-modal v-model="showProgressModal" :showConfirmButton="false" :closeOnClickOverlay="true" title="上传进度">
			<view class="progress-content">
				<view class="progress-info">
					<text class="progress-text">正在上传 {{ currentUploadIndex + 1 }}/{{ totalUploadCount }}</text>
					<text class="progress-percent">{{ uploadProgress }}%</text>
				</view>
				<uv-line-progress :percentage="uploadProgress" :round="true" activeColor="#2979ff"></uv-line-progress>
			</view>
		</uv-modal>
	</view>
</template>

<script>
	export default {
		name: "wanl-upload",
		props: {
			// 文件列表
			value: {
				type: Array,
				default: () => []
			},
			// 上传字段名
			name: {
				type: String,
				default: 'file'
			},
			// 是否多选
			multiple: {
				type: Boolean,
				default: false
			},
			// 最大上传数量
			maxCount: {
				type: Number,
				default: 10
			},
			// 上传地址
			uploadUrl: {
				type: String,
				default: '/wanlshop.common/upload'
			},
			// 是否可预览图片
			previewImage: {
				type: Boolean,
				default: true
			},
			// 是否显示删除按钮
			deletable: {
				type: Boolean,
				default: true
			},
			// 上传按钮文字
			uploadText: {
				type: String,
				default: '上传图片'
			},
			// 提示文字
			tipText: {
				type: String,
				default: '支持jpg、png格式，大小不超过2M'
			},
			// 是否显示提示
			showTip: {
				type: Boolean,
				default: true
			},
			// 是否显示预览标题
			showPreviewTitle: {
				type: Boolean,
				default: false
			},
			// 自定义上传头信息
			header: {
				type: Object,
				default: () => ({})
			},
			// 自定义上传参数
			formData: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				fileList: [],
				showProgressModal: false,
				uploadProgress: 0,
				currentUploadIndex: 0,
				totalUploadCount: 0
			};
		},
		watch: {
			value: {
				handler(newVal) {
					this.fileList = newVal;
				},
				immediate: true,
				deep: true
			},
			fileList: {
				handler(newVal) {
					this.$emit('input', newVal);
					this.$emit('change', newVal);
				},
				deep: true
			}
		},
		methods: {
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'uploading': '上传中',
					'error': '上传失败',
					'success': '上传成功'
				};
				return statusMap[status] || '';
			},

			// 新增图片
			async afterRead(event) {
				console.log('afterRead event:', event);

				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileList.length;

				// 检查是否超过最大数量
				if (fileListLen + lists.length > this.maxCount) {
					this.$wanlshop.msg(`最多只能上传${this.maxCount}张图片`);
					lists = lists.slice(0, this.maxCount - fileListLen);
				}

				// 如果是单文件上传且已经存在文件，先清空原有文件
				if (!this.multiple && this.fileList.length > 0) {
					this.fileList = [];
					fileListLen = 0;
				}

				// 添加到文件列表
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中...'
					});
				});

				// 显示上传进度
				this.showProgressModal = true;
				this.totalUploadCount = lists.length;
				this.currentUploadIndex = 0;
				this.uploadProgress = 0;

				// 逐个上传文件
				for (let i = 0; i < lists.length; i++) {
					this.currentUploadIndex = i;

					try {
						const result = await this.uploadFilePromise(lists[i].url);
						const itemIndex = fileListLen + i;

						// 更新文件状态
						this.fileList.splice(itemIndex, 1, Object.assign(this.fileList[itemIndex], {
							status: 'success',
							message: '',
							url: result.url,
							id: result.id || null,
							originalName: lists[i].name || 'image'
						}));

						// 更新进度
						this.uploadProgress = Math.round(((i + 1) / lists.length) * 100);

						// 上传成功回调
						this.$emit('upload-success', {
							file: lists[i],
							result: result,
							index: itemIndex
						});

					} catch (error) {
						console.error('上传失败:', error);
						const itemIndex = fileListLen + i;

						this.fileList.splice(itemIndex, 1, Object.assign(this.fileList[itemIndex], {
							status: 'error',
							message: error.message || '上传失败'
						}));

						// 上传失败回调
						this.$emit('upload-error', {
							file: lists[i],
							error: error,
							index: itemIndex
						});
					}
				}

				// 隐藏进度弹窗
				setTimeout(() => {
					this.showProgressModal = false;
					this.uploadProgress = 0;
				}, 500);
			},

			// 删除图片
			deletePic(event) {
				console.log('delete event:', event);
				const index = event.index;

				if (index >= 0 && index < this.fileList.length) {
					const deletedFile = this.fileList[index];
					this.fileList.splice(index, 1);

					// 删除回调
					this.$emit('delete', {
						file: deletedFile,
						index: index
					});
				}
			},

			// 手动删除图片
			handleDelete(index) {
				this.deletePic({
					index
				});
			},

			// 重新上传
			async handleReupload(file, index) {
				if (!file.url) {
					this.$wanlshop.msg('文件路径不存在');
					return;
				}

				// 更新状态为上传中
				this.fileList.splice(index, 1, Object.assign(this.fileList[index], {
					status: 'uploading',
					message: '重新上传中...'
				}));

				try {
					const result = await this.uploadFilePromise(file.url);

					this.fileList.splice(index, 1, Object.assign(this.fileList[index], {
						status: 'success',
						message: '',
						url: result.url,
						id: result.id || null
					}));

					this.$wanlshop.msg('重新上传成功');

					// 重新上传成功回调
					this.$emit('reupload-success', {
						file: file,
						result: result,
						index: index
					});

				} catch (error) {
					console.error('重新上传失败:', error);

					this.fileList.splice(index, 1, Object.assign(this.fileList[index], {
						status: 'error',
						message: error.message || '重新上传失败'
					}));

					// 重新上传失败回调
					this.$emit('reupload-error', {
						file: file,
						error: error,
						index: index
					});
				}
			},

			// 上传文件Promise
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.uploadUrl,
						filePath: url,
						name: this.name,
						header: {
							'Authorization': uni.getStorageSync('token') || '',
							...this.header
						},
						formData: {
							...this.formData
						},
						success: (res) => {
							try {
								const result = JSON.parse(res.data);

								if (result.code === 1) {
									resolve(result.data);
								} else {
									reject(new Error(result.msg || '上传失败'));
								}
							} catch (e) {
								reject(new Error('解析响应数据失败'));
							}
						},
						fail: (error) => {
							reject(new Error('网络错误，请检查网络连接'));
						}
					});
				});
			},

			// 清空所有文件
			clearFiles() {
				this.fileList = [];
				this.$emit('clear');
			},

			// 获取成功上传的文件列表
			getSuccessFiles() {
				return this.fileList.filter(item => item.status === 'success');
			},

			// 获取所有文件的URL
			getFileUrls() {
				return this.getSuccessFiles().map(item => item.url);
			},

			// 手动触发上传（用于外部调用）
			chooseImage() {
				// 这里可以触发uv-upload的内部选择图片方法
				// 由于uv-upload组件内部没有暴露chooseImage方法，我们可以通过模拟点击来实现
				const uploadComponent = this.$refs.upload;
				if (uploadComponent && uploadComponent.chooseImage) {
					uploadComponent.chooseImage();
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wanl-upload {
		width: 100%;
	}

	.upload-area {
		margin-bottom: 24rpx;

		::v-deep .uv-upload {
			width: 100%;
		}

		::v-deep .uv-upload__wrap {
			justify-content: flex-start;
		}

		.upload-custom {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 160rpx;
			height: 160rpx;
			border: 2rpx dashed #dcdfe6;
			border-radius: 12rpx;
			background-color: #fafafa;
			transition: all 0.3s ease;

			&:active {
				background-color: #f5f7fa;
				border-color: #c0c4cc;
			}

			.upload-icon {
				margin-bottom: 12rpx;

				.iconfont {
					font-size: 40rpx;
					color: #c0c4cc;
				}
			}

			.upload-text {
				font-size: 22rpx;
				color: #606266;
				margin-bottom: 6rpx;
			}

			.upload-tip {
				font-size: 20rpx;
				color: #909399;
				text-align: center;
				line-height: 1.4;
				padding: 0 10rpx;
			}
		}
	}

	.progress-content {
		padding: 30rpx;

		.progress-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.progress-text {
				font-size: 28rpx;
				color: #303133;
			}

			.progress-percent {
				font-size: 28rpx;
				color: #2979ff;
				font-weight: 600;
			}
		}
	}
</style>